package com.sunxueqi.framework.security.service;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import com.sunxueqi.common.constant.StatusConstants;
import com.sunxueqi.common.exception.UserException;
import com.sunxueqi.common.utils.MessageUtils;
import com.sunxueqi.framework.manager.AsyncFactory;
import com.sunxueqi.framework.security.LoginUser;

import cn.hutool.core.thread.ThreadUtil;

@Component
public class LoginService {

	@Autowired
	private TokenService tokenService;
	
	@Resource
    private AuthenticationManager authenticationManager;
	
	public String login(String username, String password, String code, String uuid) {
		Authentication authentication = null;
		try {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername()
            authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
        } catch (Exception e) {
        	System.out.println(e);
        	System.out.println(e instanceof UserException);
        	System.out.println(e instanceof BadCredentialsException);
        	System.out.println(e instanceof BadCredentialsException);
        	System.out.println(e instanceof InternalAuthenticationServiceException);
        	
        	
        	if(e instanceof BadCredentialsException) {
        		// todo 记录log
        		throw new UserException("user.password.not.match");
        	}
//        	else {
////        		// todo 记录log
//        		throw new CustomException(e.getMessage());
//        	}
        	
        	throw new UserException("user.not.exist");
        }
		ThreadUtil.execAsync(AsyncFactory.recordLoginLog(username, StatusConstants.SUCCESSFUL, MessageUtils.message("user.login.success")), true);
		LoginUser loginUser = (LoginUser) authentication.getPrincipal();
		return tokenService.createToken(loginUser);
	}
}
